package com.sx.mvvmlibs.base

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.sx.mvvmlibs.app.AppActivityManager
import com.sx.mvvmlibs.base.BaseApp.Companion.initApp


/**
 * @Author: YY
 * @Date: 2022/1/5
 * @Describe: Application基类
 * TODO: 如项目Application不继承此基类，必须调用 [initApp] 方法，否则使用工具类会导致 Context空异常
 */
open class BaseApp : Application() {

    override fun onCreate() {
        super.onCreate()
        initApp(this)
    }

    companion object {
        private lateinit var mApplication: Application

        @JvmStatic
        fun initApp(app: Application) {
            mApplication = app
            // 初始化资源加载
            initResource(app)
        }

        @JvmStatic
        fun getInstance(): Application {
            return mApplication
        }

        private fun initResource(app: Application) {
            app.registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {

                override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                    AppActivityManager.addActivity(activity)
                }

                override fun onActivityStarted(activity: Activity) {

                }

                override fun onActivityResumed(activity: Activity) {

                }

                override fun onActivityPaused(activity: Activity) {

                }

                override fun onActivityStopped(activity: Activity) {
                }

                override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
                }

                override fun onActivityDestroyed(activity: Activity) {
                    AppActivityManager.removeActivity(activity)
                }

            })
        }
    }

}